#include "Common.h"
#include "pthread_function.h"
#include "type.h"
#include "TcpServerSession.h"
#include "TcpClientSession.h"

void* create_tcp_srv_thread(void* arg)
{
#ifdef DEBUG_PTHREAD_FUNCTION
	cout<<"create a new thread "<<pthread_self()<<" for tcp server connection."<<endl;
#endif

	TCP_CONN_SOCK_INFO* ptr_conn_info = (TCP_CONN_SOCK_INFO*)arg;
	TcpServerSession* ptr_tcp_srv_session = ptr_conn_info->ptr_tcp_srv_session;
	ptr_tcp_srv_session->execute_srv_protocol(&(ptr_conn_info->conn_sock));

	if(NULL != ptr_conn_info) {
		delete ptr_conn_info;
	}

//	close(*(ptr_conn_info->ptr_conn_sock));
#ifdef DEBUG_PTHREAD_FUNCTION
	cout<<"tcp server connection thread "<<pthread_self()<<" exit."<<endl;
#endif

	return NULL;
}

void* create_tcp_cli_thread(void* arg)
{
#ifdef DEBUG_PTHREAD_FUNCTION
	cout<<"create a new thread "<<pthread_self()<<" for tcp client connection."<<endl;
#endif
	int ret_val;
	TcpClientSession* cli_ptr = (TcpClientSession*)arg;

	ret_val = cli_ptr->cli_connect();
	if(-1 == ret_val) {
		cout<<"Thread:"<<pthread_self()<<"Fail to start a tcp client session."<<endl;
		cout<<"Thread "<<pthread_self()<<" exit."<<endl;
		return NULL;
	}

	cli_ptr->execute_cli_protocol();

#ifdef DEBUG_PTHREAD_FUNCTION
	cout<<"tcp client connection thread "<<pthread_self()<<" exit."<<endl;
#endif

	return NULL;
}

void* create_tcp_srv_listen_thread(void* arg)
{
#ifdef DEBUG_PTHREAD_FUNCTION
	cout<<"create a new thread "<<pthread_self()<<" for TCP server listening session."<<endl;
#endif

	int ret_val;
	TcpServerSession* srv_ptr = (TcpServerSession*)arg;

	ret_val = srv_ptr->srv_start();
	if(-1 == ret_val) {
		cout<<"Thread:"<<pthread_self()<<"Fail to start a TCP server listening session."<<endl;
		cout<<"Thread "<<pthread_self()<<" exit."<<endl;
		return NULL;
	}

#ifdef DEBUG_PTHREAD_FUNCTION
	cout<<"tcp client connection thread "<<pthread_self()<<" exit."<<endl;
#endif

	return NULL;
}
